package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.UserThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 删除图片素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deletePicture(Integer id) {
        //1.检擦参数
        if (id == null || id <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取素材对象
        WmMaterial wmMaterial = baseMapper.selectById(id);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String url = wmMaterial.getUrl();
        //3.删除minio中的素材
        fileStorageService.delete(url);
        //4.删除数据库中的素材
        baseMapper.deleteById(id);
        //5.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消图片收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult unCollectPicture(Integer id) {
        //1.检查参数
        if (id == null || id <= 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.取消收藏
        WmMaterial wmMaterial = lambdaQuery().eq(WmMaterial::getId, id).one();
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.取消收藏
        wmMaterial.setIsCollection((short)0);
        baseMapper.updateById(wmMaterial);
        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 图片上传
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        log.info("【检查参数】:{}",multipartFile);
        if(multipartFile==null && multipartFile.isEmpty()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID); //无效参数
        }
        //2.上传图片到minio中
        //去掉随机生成id中的 - 符号
        String fileName = UUID.randomUUID().toString().replace("-","");
        //获取图片后缀
        String originalFilename = multipartFile.getOriginalFilename();
        String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileUrl = null;
        try {
            fileUrl = fileStorageService.uploadImgFile("", fileName + prefix, multipartFile.getInputStream());
        } catch (IOException e) {
            log.error("上传文件失败: {}",e);
        }
        log.info("【上传图片到minio】:{}",fileUrl);
        //3.保存到数据库中
        log.info("【保存数据到数据库中】");
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(fileUrl);
        wmMaterial.setType((short)0);
        wmMaterial.setUserId(UserThreadLocalUtil.getUser());
        wmMaterial.setIsCollection((short)0);
        save(wmMaterial);
        //返回结果
        log.info("【返回结果】:{}",wmMaterial);
        return ResponseResult.okResult(wmMaterial);

    }

    /**
     * 查询图片列表
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto wmMaterialDto) {
        //1.检查参数
        log.info("【wmMaterialDto】检查参数:{}",wmMaterialDto);
        if(wmMaterialDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmMaterialDto.checkParam();
        //2.分页查询
        log.info("【开始分页查询】");
        IPage page = new Page(wmMaterialDto.getPage(),wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //是否收藏
        if(wmMaterialDto.getIsCollection() ==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,1);
        }
        //根据用户id查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId,UserThreadLocalUtil.getUser());

        //根据创建时间倒叙排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        page = page(page, lambdaQueryWrapper);
        log.info("【分页查询结果】:{}",page.getRecords());
        //向上转型
        ResponseResult responseResult = new PageResponseResult(wmMaterialDto.getPage(), wmMaterialDto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        log.info("【查询结束】:返回结果为{}",responseResult);
        return responseResult;
    }

    /**
     * 收藏图片素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectPicture(Integer id) {
        //1.检验参数
        if(id==null || id<=0){
            log.info("【无效参数】");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据图片id设置收藏
        WmMaterial wmMaterial = baseMapper.selectById(id);
        if(wmMaterial==null){
            log.info("【数据不存在】");
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmMaterial.setIsCollection((short)1);
        baseMapper.updateById(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }
}

